package com.fxb.learn.direct_buff.mapped_buffer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;

/**
 * @author fangjiaxiaobai
 * @date 2022-05-29 10:16
 */
public class MappedByteBufferDemo {

    public static void main(String[] args) throws IOException {
        String filePath = "/Users/wangxiyue/Documents/fxb_application/learn_java/fxb_jdk11/ch11-nio_demo/target/classes/com/fxb/learn/direct_buff/demo.txt";
        RandomAccessFile raf = new RandomAccessFile(new File(filePath), "rw");
        FileChannel channel = raf.getChannel();
        System.out.println("FileChannel.size: " + channel.size());
        MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, (int) channel.size());

        FileLock lock = channel.lock();
        byte[] bytes = new byte[(int) channel.size()];
        mappedByteBuffer.get(bytes);
        System.out.println("读取的内容: " + new String(bytes));
        lock.release();

        System.out.println("读取之后的 position: " + mappedByteBuffer.position());
        byte[] inputBytes = "\n建军回来了?".getBytes(StandardCharsets.UTF_8);
        ByteBuffer byteBuffer = ByteBuffer.wrap(inputBytes);
        MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, mappedByteBuffer.position() + inputBytes.length);
        map.position(mappedByteBuffer.position());
        FileLock lock1 = channel.lock();
        map.put(byteBuffer);
        lock1.release();
        channel.close();
        System.out.println("写入完成..");

    }


}
